let lyricText = '',
    againLyric = '',
    new_word = '',
    ori_word = '',
    curr_id = '',
    word_type = '',
    ori_file = '',
    uptype = '',
    isUpFile = false,
    wordName = {}
const db = wx.cloud.database()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        ori_lyric: "",
        flieName: "",
        filePath: "",
        new_word: ''
    },

    /**
     * 1. 判断是否复用音频
     * 2. 有的话，取出已缓存的cloudID、第一次使用的单词名称
     * 3. 从数据库查询当前单词的数据，判断是否有音频和歌词
     */
    async onLoad(options) {
        new_word = options.content
        curr_id = options.id
        word_type = options.type
        uptype = options.uptype
        console.log('options', curr_id, word_type, uptype)
        this.setData({
            word: options.content,
        })
        // 查看上传类型
        if (uptype == 'againUp') {
            let res = wx.getStorageSync('again_up')
            isUpFile = true // 判断是否有音频文件
            console.log(res)
            ori_file = res.address
            ori_word = res.content // 使用上传的名称
            againLyric = res.lyric
            console.log('ori_file', ori_file, ori_word)
            this.setData({
                ori_lyric:againLyric,
                ori_file: true,
                currName: res.content + '的原音频'
            })
        } else {
            if (wx.getStorageSync('cloudId')) {
                let res = wx.getStorageSync('cloudId')
                ori_file = JSON.parse(res.ori_file)
                isUpFile = true // 判断是否有音频文件
                ori_word = res.ori_word // 使用第一次上传的名称
                againLyric = res.lyricText // 使用歌词
                console.log('ori_file', ori_file, ori_word)
                this.setData({
                    ori_file: true,
                    ori_lyric:againLyric,
                    currName: ori_word
                })
            }
        }
        // lyric = wordName.lyric // TODO 歌词数据以获取
        // address = wordName.address
        // console.log(lyric, address)
    },

    lyric(e) {
        lyricText = e.detail.value ? e.detail.value : againLyric
        console.log(lyricText)
    },
    setClipboardData() { // 复制歌词
        wx.setClipboardData({
            data: againLyric,
            success(res) {
                wx.getClipboardData({
                    success(res) {
                        console.log(res.data) // data
                    }
                })
            }
        })
    },


    /**
     * 1. 不复用音频则重新选择音频
     * 2. 移除之前缓存，获取临时路径
     */
    async chooseMessageFile() {
        console.log('uptype', uptype)
        if (uptype == "firstUp") {
            ori_file = '' // 重新选择其他音频
            ori_word = ''
            console.log('重新选择的ori_file', ori_file)
            wx.removeStorage({
                key: 'cloudId',
                success(res) {
                    console.log(res)
                }
            })
            await wx.chooseMessageFile({
                count: 1,
                type: 'file',
                extension: ['mp3'],
            }).then(res => {
                console.log('msgfile', res);
                let tempfileSize = res.tempFiles[0].size;
                if (tempfileSize <= 600000) { // 600kb
                    isUpFile = true
                    this.setData({
                        ori_file: false,
                        filePath: res.tempFiles[0].path,
                        flieName: res.tempFiles[0].name
                    })
                } else {
                    wx.showToast({
                        title: '建议音频不要超过600kb哦!',
                        icon: 'none'
                    })
                }

            })
        } else if (uptype == "againUp") {
            new_word = ori_word
            ori_word = ''
            console.log('new_word',new_word,'ori_word',ori_word)
            // 退出重新上传的类型如果上传新的音频，类型要标记为第一次上传
            await wx.chooseMessageFile({
                count: 1,
                type: 'file',
                extension: ['mp3'],
            }).then(res => {
                console.log('msgfile', res);
                let tempfileSize = res.tempFiles[0].size;
                if (tempfileSize <= 600000) { // 600kb
                    isUpFile = true
                    this.setData({
                        ori_file: false,
                        filePath: res.tempFiles[0].path,
                        flieName: res.tempFiles[0].name
                    })
                } else {
                    wx.showToast({
                        title: '建议音频不要超过600kb哦!',
                        icon: 'none'
                    })
                }
            })
        }
    },

    /**
     * 1. 判断是否为新的音频地址
     * 2. 若是新的音频地址，重新转buffer流上传到云函数
     * 3. 若不是新的音频地址，直接跳过云函数中生成fileID那步
     */
    async submit() {
        console.log('isUpFile',isUpFile)
        if (isUpFile && lyricText) {
            const {
                filePath
            } = this.data
            // let bufferAdo = ''
            // 处理loading过快消失的bug，可能和微信执行的顺序有关，打开上传文件会刷新页面

            wx.showLoading({
                title: '音频上传中...',
                mask: false
            })
            // 复用地址
            console.log('file', filePath, new_word)

            console.log(uptype,lyricText, new_word,wx.getStorageSync('userInfo').openid,wx.getStorageSync('userInfo').userInfo.nickName)
            // return
            await wx.cloud.callFunction({ // 上传
                name: 'userUpFile',
                data: {
                    newfileID: ori_word ? false : true, // 判断是否需要新的fileID
                    word: ori_word ? ori_word : new_word, // 复用
                    currword: new_word,
                    // type: word_type, // 单词（暂时不用）
                    path: filePath?wx.cloud.CDN({
                        type:"filePath",
                        filePath:filePath
                    }):ori_file , // 音频
                    lyric: lyricText, // 歌词
                    user: wx.getStorageSync('userInfo').userInfo.nickName,
                    type: uptype == 'firstUp' ? 'first_up' : 'again_up', // 上传类型
                    status: 'checking' // 单词状态 checking审核中，success成功，fail失败
                }
            }).then((res) => { // TODO
                console.log(res)
                let cloudfileId = res.result // 返回云地址
                console.log(cloudfileId !== ori_file, cloudfileId)
                if (cloudfileId !== ori_file) { // 判断是否更换了音频
                    wx.setStorageSync('cloudId', {
                        ori_word: new_word,
                        lyricText:lyricText,
                        ori_file: JSON.stringify(cloudfileId),
                        currName: this.data.flieName
                    })
                }
                wx.showToast({
                    title: '上传成功，等待审核',
                    icon: 'none'
                })
                wx.hideLoading()
                console.log(wordName.content, curr_id)
                wx.navigateBack()
                // wx.navigateTo({
                //   url: '../dictionary/wordDetail/wordDetail?content=' + new_word + '&id=' + curr_id,
                // })
            })
        } else {
            wx.showModal({
                title: '音频或者歌词没有填写完整哦',
                showCancel:false,
                success(res) {
                    if (res.confirm) {
                        console.log("用户点击确定")
                    }
                }
            })
        }
    },

    onUnload(){
        ori_file = ''
        console.log('退出后的ori_file',ori_file)
    }
})